package ljl.codetop300;

import java.util.Arrays;

public class _443_compress {

  static class test {
    public static void main(String[] args) {
      char[] ch = "aabbccc".toCharArray();
      System.out.println(new test().compress(ch));
      System.out.println(Arrays.toString(ch));
    }
    public int compress(char[] chars) {
      int i = 0;
      int count = 1;
      char c = chars[0];
      for (int k = 1; k < chars.length; k++) {
        if (c != chars[k]) {
          chars[i++] = c;
          if (count != 1) {
            String num = String.valueOf(count);
            for (int l = 0; l < num.length(); l++) {
              chars[i++] = num.charAt(l);
            }
          }
          c = chars[k];
          count = 1;
        } else {
          count++;
        }
      }
      chars[i++] = c;
      if (count != 1) {
        String num = String.valueOf(count);
        for (int l = 0; l < num.length(); l++) {
          chars[i++] = num.charAt(l);
        }
      }
      return i;
    }
  }

  static class off {
    public int compress(char[] chars) {
      int n = chars.length;
      int write = 0, left = 0;
      for (int read = 0; read < n; read++) {
        if (read == n - 1 || chars[read] != chars[read + 1]) {
          chars[write++] = chars[read];
          int num = read - left + 1;
          if (num > 1) {
            int anchor = write;
            while (num > 0) {
              chars[write++] = (char) (num % 10 + '0');
              num /= 10;
            }
            reverse(chars, anchor, write - 1);
          }
          left = read + 1;
        }
      }
      return write;
    }

    public void reverse(char[] chars, int left, int right) {
      while (left < right) {
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
      }
    }
  }

  static class copyoff {
    public static void main(String[] args) {
      char[] chars = "aaabbbccv".toCharArray();
      System.out.println(new copyoff().compress(chars));
      System.out.println(Arrays.toString(chars));
    }
    public int compress(char[] chars) {
      int writeIndex = 0;
      int start = 0;
      for (int i = 0; i < chars.length; i++) {
        if (i == chars.length - 1 || chars[i] != chars[i + 1]) {
          chars[writeIndex++] = chars[start];
          int count = i - start + 1;
          if (count > 1) {
            int from = writeIndex;
            while (count > 0) {
              chars[writeIndex++] = (char) (count % 10 + '0');
              count /= 10;
            }
            reverse(chars, from, writeIndex - 1);
          }

          start = i + 1;
        }
      }
      return writeIndex;
    }
    void reverse(char[] chars, int left, int right) {
      while (left < right) {
        char t = chars[left];
        chars[left] = chars[right];
        chars[right] = t;
        left++;
        right--;
      }
    }

  }
}
